package com.oedtech.esl.service.securityService;

import com.oedtech.esl.json.JsonResult;
import com.oedtech.esl.model.sys.Store;
import com.oedtech.esl.model.sys.StoreBsid;
import com.oedtech.esl.repository.sys.StoreBsidDao;
import com.oedtech.esl.repository.sys.StoreDao;
import com.oedtech.esl.repository.sys.UserDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Example;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.FileCopyUtils;

import javax.transaction.Transactional;
import java.io.File;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

@Service
public class StoreService {

    public final static Map<String, String> storeMap = new ConcurrentHashMap<>();
    @Value("${channelList}")
    private String channelList;

    @Autowired
    private UserDao userDao;
    @Autowired
    private StoreDao storeDao;
    @Autowired
    private StoreBsidDao storeBsidDao;


    private final static String[]CODELIST={"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z",
            "1","2","3","4","5","6","7","8","9"};
    private final static Random RANDOM=new Random();
    private static String createCode(){
        int n;
        StringBuilder sb=new StringBuilder();
        for(int i=0;i<5;i++){
            n=RANDOM.nextInt(35);
            sb.append(CODELIST[n]);
        }

        return sb.toString();

    }
    private String generateVendorCode(){
        String str=UUID.randomUUID().toString();
        return str.substring(str.lastIndexOf("-")+1);
    }

    /**
     * 增加或修改门店
     * @param store  门店类
     * @return
     * @throws IOException
     */
    @Transactional
    public JsonResult addOrChangeStore(Store store) throws IOException {
        if(store.getPassword()==null)return new JsonResult("error","密码不能为空");

        if(store.getStoreName()==null)return new JsonResult("error","门店名不能为空");
        boolean newStore=false; //标识是否是新创建的店
        Authentication auth= SecurityContextHolder.getContext().getAuthentication();
        String username=auth.getName();
        if(store.isNewStoreFlag()){  //判断是否为新创建门店

            newStore=true;
            store.setPassword(new BCryptPasswordEncoder().encode(store.getPassword()));   //密码加密

            store.setChannelList(channelList);

            Integer sourceFlag=userDao.findSourceFlagByUsername(username);//获取本当前登陆的用户下的资源标识
            if(sourceFlag==0){
                if(store.getSourceFlag()==null||store.getSourceFlag()==0)return new JsonResult("error","资源标识不能空或0");
            }else{
                store.setSourceFlag(sourceFlag);
            }
            if(storeDao.existsByStoreName(store.getStoreName()))return new JsonResult("error","门店名称已存在");
            if(store.getStoreCode()==null){    //门店编码为空则自动生成，否则判断门店编码是否已存在
                String storeCode;
                while(true){
                    storeCode=createCode();
                    if(!storeDao.existsById(storeCode)){
                        break;
                    }
                }
                store.setStoreCode(storeCode);
            }else {
                if(store.getStoreCode().trim().isEmpty()||store.getStoreCode().length()<4||!store.getStoreCode().matches("[A-Z,0-9]+"))return new JsonResult("error","门店编码必须大于4位的大写字母或数字");
                if(storeDao.existsById(store.getStoreCode()))return new JsonResult("error","门店编码重复");
            }

        }


        store.setModifyTime(new Date());
        store.setModifyWho(username);
        storeDao.save(store);
        return new JsonResult("success","保存成功");
    }

    @Transactional
    public void deleteStore(String storeCode){
        storeDao.deleteById(storeCode);
//        pluTabDao.deleteByStoreCode(storeCode);


        List<String> storeCodeList = new ArrayList<>();
        storeCodeList.add(storeCode);
        storeMap.values().removeAll(storeCodeList);

    }


    @Transactional
    public JsonResult relateBsid(String bsId,String storeCode,String username){
        if(bsId==null)return new JsonResult("error","基站ID不能为空");
        if(storeBsidDao.findCountByBsId(bsId)>0) return new JsonResult("error","基站重复关联");
        StoreBsid storeBsid=new StoreBsid();
        storeBsid.setApId(bsId);
        storeBsid.setStoreCode(storeCode);
        storeBsidDao.save(storeBsid);
        storeDao.saveModify(username, storeCode);
        storeMap.put(bsId, storeCode);
           return new JsonResult("success",storeBsid,null);

    }

    public JsonResult deleteRelate(String username,String storeCode,String bsid){
        storeBsidDao.deleteById(bsid);
        List<StoreBsid> list=storeBsidDao.findByStoreCode(storeCode);
        storeDao.saveModify(username, storeCode);

        storeMap.remove(bsid);
        return new JsonResult("success",list,null);
    }



    private void deleteFile(File file) {
        if(file.exists()){
            if(file.isFile()){
                file.delete();
            }else  if(file.isDirectory()){
                File[]files=file.listFiles();
                for(File file1:files){
                    deleteFile(file1);
                }
                file.delete();
            }
        }
    }


    public Store checkStoreLogin(String storeCode,String password){
        Store store=storeDao.findByStoreCode(storeCode);
        if(store==null)return null;
        boolean b=new BCryptPasswordEncoder().matches(password,store.getPassword());
        if(b){
            return store;
        }
        return null;
    }



    public void saveStore(String storeCode){
        if(storeDao.findById(storeCode).orElse(null)!=null)
            return;
        Store store = new Store();
        store.setStoreCode(storeCode);
        store.setChannelList(channelList);
        store.setStoreName(storeCode);
        store.setPassword("111111");
        store.setSourceFlag(10);
        store.setModifyTime(new Date());
        storeDao.save(store);
    }
}
